package gatewayRouter

import (
	"errors"
	"strings"
)

type RouterVO struct {
	Id         string                   `json:"id"`         // json字段
	Uri        string                   `json:"uri"`        // json字段
	Order      int                      `json:"order"`      // json字段
	Predicates []map[string]interface{} `json:"predicates"` // json字段
	Filters    []map[string]interface{} `json:"filters"`    // json字段
	Metadata   map[string]interface{}   `json:"metadata"`   // json字段
}

// BuildVO 使用范例：BuildVO("service","channel-serialport-native","/service/channel-serialport-native/**",""http://localhost:9201/service/channel-serialport-native")
func (e *RouterVO) buildVO(serviceType string, serviceName string, serviceUri string, redirectUri string) *RouterVO {
	vo := &RouterVO{}
	vo.Id = serviceType + ":" + serviceName
	vo.Uri = redirectUri
	vo.Metadata = make(map[string]interface{})
	vo.Order = 0

	// predicates
	vo.Predicates = make([]map[string]interface{}, 0)
	predicate := make(map[string]interface{})
	predicate["name"] = "Path"
	args := make(map[string]interface{})
	args["_genkey_0"] = serviceUri
	predicate["args"] = args
	vo.Predicates = append(vo.Predicates, predicate)

	// filters
	vo.Filters = make([]map[string]interface{}, 0)
	filters := make(map[string]interface{})
	filters["name"] = "StripPrefix"
	args = make(map[string]interface{})
	args["_genkey_0"] = 2
	filters["args"] = args
	vo.Filters = append(vo.Filters, filters)

	return vo
}

func (e *RouterVO) getParams() (string, string, string, error) {
	if len(e.Predicates) == 0 {
		return "", "", "", errors.New("predicates缺失")
	}

	predicate := e.Predicates[0]
	val, ok := predicate["args"]
	if !ok {
		return "", "", "", errors.New("predicates.args缺失")
	}
	args := val.(map[string]interface{})

	val, ok = args["_genkey_0"]
	if !ok {
		return "", "", "", errors.New("predicates.args._genkey_0缺失")
	}
	serviceUri := val.(string)

	// 分拆数据：获得http://localhost:9101/kernel/manager中的http://localhost:9101部分
	idx := strings.Index(e.Uri, "://") + len("://")
	idx += strings.Index(e.Uri[idx:len(e.Uri)], "/")
	uri := e.Uri[0:idx]

	return e.Id, uri, serviceUri, nil
}
